'use client';
import React, { useEffect, useState } from 'react';
import { 
  Table, 
  Button, 
  Card, 
  Space, 
  Tag, 
  Input, 
  Modal, 
  message, 
  Typography, 
  Popconfirm,
  Tooltip,
  Divider,
  Row,
  Col
} from 'antd';
import { 
  SearchOutlined, 
  EyeOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { articleService, Article } from '@/service/article.service';
import parse from 'html-react-parser';
import { countdownValueType } from 'antd/es/statistic/utils';
import { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Search } = Input;

interface TagItem {
  id: string | number;
  name: string;
}

const ArticleSH: React.FC = () => {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
  const [previewVisible, setPreviewVisible] = useState(false);

  const statusMap = new Map<number, { text: string; color: string }>([
  [0, { text: '审核失败', color: 'red' }],
  [1, { text: '审核成功', color: 'green' }],
  [-1, { text: '待审核', color: 'gray' }],
]);

  // 加载待审核文章列表
  const loadPendingArticles = async () => {
    setLoading(true);
    try {
      const response = await articleService.getArticleList({
        page: currentPage,
        pageSize: pageSize,
        keyword: searchKeyword,
        isActive: -1 // 审核状态过滤（-1表示不过滤）
      });
      
  
      // 根据实际API响应格式调整
      const articlesData = response.data || response || [];
      const totalCount = response.total || 0;
      // console.log('文章列表数据:', articlesData)
      setArticles(Array.isArray(articlesData) ? articlesData : []);
      setTotal(totalCount);
      
    
    } catch (error: unknown) {
      console.error('加载待审核文章失败:', error);

      // 显示模拟数据用于测试
      const mockData = [
        {
          id: 1,
          title: '测试文章标题',
          username: '测试作者',
          category: { name: '测试分类' },
          tags: [{ id: 1, name: '测试标签' }],
          isActive: -1,
          createdAt: new Date().toISOString(),
          content: '这是测试文章内容',
        }
      ];
      setArticles(mockData as []);
      setTotal(1);
    } finally {
      setLoading(false);
    }
  };

  // 审核文章
  const reviewArticle = async (id: number, status: number) => {
    try {
      console.log('审核文章:', { id, status }); // 调试日志
      
      // 调用真实API进行审核操作
      await articleService.updateArticleStatus(id, status);
      
      const statusText = status === 1 ? '审核通过' : '审核不通过';
      message.success(`文章${statusText}`);
      
      // 从列表中移除已审核的文章
      setArticles(prev => prev.filter(article => article.id !== id));
      setTotal(prev => prev - 1);
      
      // 如果详情模态框打开的是当前文章，关闭它
      if (selectedArticle && selectedArticle.id === id) {
        setPreviewVisible(false);
        setSelectedArticle(null);
      }
      
    } catch (error: unknown) {
      console.error('审核文章失败:', error);
    
    }
  };

  // 查看文章详情
  const viewArticleDetail = async (id: number) => {
    try {
      console.log('查看文章详情:', id); // 调试日志
      const article = await articleService.getArticleDetail(id);
      console.log('文章详情:', article); // 调试日志
      setSelectedArticle(article as Article);
      setPreviewVisible(true);
    } catch (error: unknown) {
      console.error('获取文章详情失败:', error);

    }
  };

  // 搜索处理
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  // 分页变化
  const handlePageChange = (page: number, size?: number) => {
    setCurrentPage(page);
    if (size) setPageSize(size);
  };

  // 初始化加载
  useEffect(() => {
    loadPendingArticles();
  }, [currentPage, pageSize, searchKeyword]);

  // 表格列配置
  const columns: ColumnsType<Article>= [
    {
      title: '文章标题',
      dataIndex: 'title',
      key: 'title',
      width: 300,
      ellipsis: true,
      render: (text: string, record: Article) => (
        <Tooltip title={text}>
          <Text 
            strong 
            style={{ cursor: 'pointer', color: '#1890ff' }}
            onClick={() => viewArticleDetail(record.id)}
          >
            {text}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: '作者',
      dataIndex: 'username',
      key: 'username',
      width: 120,
      render: (username: string) => username || '未知作者',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category: { name: string }) => category?.name || '未分类',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 150,
      render: (tags: TagItem[]) => (
        <Space wrap size={[0, 8]}>
          {tags?.slice(0, 2).map(tag => (
            <Tag key={tag.id}>{tag.name}</Tag>
          ))}
          {tags && tags.length > 2 && <Tag >+{tags.length - 2}</Tag>}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (status: number) => {
      // 使用类型守卫
         const statusInfo = statusMap.get(status);
        if (statusInfo) {
          return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
        }
        return <Tag color="default">未知状态</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (time: string) => new Date(time).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right' as const,
      render: (_: any, record: Article) => (
        <Space size="small">
          <Tooltip title="查看文章详情">
            <Button 
              type="link" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => viewArticleDetail(record.id)}
            />
          </Tooltip>
          
          <Tooltip title="审核通过">
            <Popconfirm
              title="确定审核通过吗？"
              description="文章将通过审核并对外发布"
              onConfirm={() => reviewArticle(record.id, 1)}
              okText="确定"
              cancelText="取消"
              icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
            >
              <Button 
                type="link" 
                icon={<CheckCircleOutlined />} 
                size="small"
                style={{ color: '#52c41a' }}
              />
            </Popconfirm>
          </Tooltip>
          
          <Tooltip title="审核不通过">
            <Popconfirm
              title="确定审核不通过吗？"
              description="文章将标记为审核失败"
              onConfirm={() => reviewArticle(record.id, 0)}
              okText="确定"
              cancelText="取消"
              icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
            >
              <Button 
                type="link" 
                icon={<CloseCircleOutlined />} 
                size="small"
                danger
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <Card>
        {/* 页面标题和统计信息 */}
        <div className="mb-6">
          <Row justify="space-between" align="middle">
            <Col>
              <Title level={2} style={{ margin: 0 }}>文章审核</Title>
              <Text type="secondary">管理待审核的文章内容</Text>
            </Col>
            <Col>
              <Tag color="orange" style={{ fontSize: '14px', padding: '4px 8px' }}>
                待审核文章: {total} 篇
              </Tag>
            </Col>
          </Row>
        </div>

        <Divider />

        {/* 搜索和操作区域 */}
        <div className="mb-4">
          <Row justify="space-between" align="middle">
            <Col>
              <Search
                placeholder="搜索文章标题或内容"
                allowClear
                enterButton={<SearchOutlined />}
                size="middle"
                style={{ width: 300 }}
                onSearch={handleSearch}
              />
            </Col>
            <Col>
              <Space>
                <Button 
                  icon={<ReloadOutlined />} 
                  onClick={loadPendingArticles}
                  loading={loading}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 文章列表表格 */}
        {articles.length === 0 && !loading ? (
          <div style={{ 
            textAlign: 'center', 
            padding: '60px 20px',
            backgroundColor: '#fafafa',
            borderRadius: '8px'
          }}>
            <div style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }}>
              📝
            </div>
            <Text type="secondary" style={{ fontSize: '16px' }}>
              暂无待审核文章
            </Text>
            <br />
            <Text type="secondary">
              当前没有需要审核的文章内容
            </Text>
            <br />
            <Button 
              type="primary" 
              onClick={loadPendingArticles}
              style={{ marginTop: '16px' }}
            >
              重新加载
            </Button>
          </div>
        ) : (
          <Table
            columns={columns}
            dataSource={articles}
            rowKey="id"
            loading={loading}
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              onChange: handlePageChange,
              onShowSizeChange: handlePageChange,
            }}
            scroll={{ x: 1000 }}
            locale={{
              emptyText: '暂无数据'
            }}
          />
        )}
      </Card>

      {/* 文章详情预览模态框 */}
      <Modal
        title={
          <Space>
            <Text strong>文章详情</Text>
            {selectedArticle && (
              <Tag color={statusMap.get(selectedArticle.isActive).color}>
                {statusMap.get(selectedArticle.isActive).text}
              </Tag>
            )}
          </Space>
        }
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={800}
        footer={[
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>,
          selectedArticle && selectedArticle.isActive === -1 && (
            <Space key="actions">
              <Popconfirm
                title="确定审核通过吗？"
                onConfirm={() => {
                  reviewArticle(selectedArticle.id, 1);
                  setPreviewVisible(false);
                }}
              >
                <Button type="primary" icon={<CheckCircleOutlined />}>
                  审核通过
                </Button>
              </Popconfirm>
              <Popconfirm
                title="确定审核不通过吗？"
                onConfirm={() => {
                  reviewArticle(selectedArticle.id, 0);
                  setPreviewVisible(false);
                }}
              >
                <Button danger icon={<CloseCircleOutlined />}>
                  审核不通过
                </Button>
              </Popconfirm>
            </Space>
          )
        ]}
      >
        {selectedArticle && (
          <div style={{ maxHeight: '60vh', overflow: 'auto' }}>
            <div className="mb-4">
              <Text strong>标题: </Text>
              <Text>{selectedArticle.title}</Text>
            </div>
            
            <div className="mb-4">
              <Text strong>作者: </Text>
              <Text>{selectedArticle.username || '未知作者'}</Text>
            </div>
            
            <div className="mb-4">
              <Text strong>分类: </Text>
              <Text>{selectedArticle.category?.name || '未分类'}</Text>
            </div>
            
            <div className="mb-4">
              <Text strong>标签: </Text>
              <Space wrap>
                {selectedArticle.tags?.map(tag => (
                  <Tag key={tag.id}>{tag.name}</Tag>
                )) || '无标签'}
              </Space>
            </div>
            
            <div className="mb-4">
              <Text strong>摘要: </Text>
              <Text>{selectedArticle.summary || '无摘要'}</Text>
            </div>
            
            <div className="mb-4">
              <Text strong>创建时间: </Text>
              <Text>{new Date(selectedArticle.createdAt).toLocaleString()}</Text>
            </div>
            
            <div>
              <Text strong>文章内容: </Text>
              <div 
                style={{ 
                  marginTop: '8px',
                  padding: '12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '6px',
                  backgroundColor: '#fafafa',
                  minHeight: '200px',
                  lineHeight: '1.6'
                }}
              >
                {selectedArticle.content ? parse(selectedArticle.content) : '无内容'}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ArticleSH;